package com.maori.languageapp.discover.word;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.maori.languageapp.R;
import com.maori.languageapp.adapter.Languageapp_Curate_VideoView_Activity;
import com.maori.languageapp.consts.ImageLoader;
import com.maori.languageapp.discover.word.Maori_Discover_Word_Details;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class Maori_Discover_VideoList_Word_Adapter extends BaseAdapter {
	// Declare Variables
	Context context;
	LayoutInflater inflater;
	ArrayList<HashMap<String, String>> data;
	ArrayList<HashMap<String, String>> arraylist;
	JSONArray jsonarray;
	// Button videoview_example;
	ImageLoader imageLoader;
	String UserLikedVideo, VideoParentNID, MediaUID,NodeMediaType;
	String VideoParentUID, VideoNID, VideoParentNodeId, VideoLikedByUser,VideoMediaID,
			result,TotalsSetDefaultVideo,SynUserID,SynNodeId,SynParentNodeId,SynMediaType,NodeMediaSourceUrl;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	InputStream is = null;
	StringBuilder sb = null;
	private LayoutInflater mInflater;
	HashMap<String, String> resultp = new HashMap<String, String>();

	public Maori_Discover_VideoList_Word_Adapter(Context context,
			ArrayList<HashMap<String, String>> arraylist) {
		this.context = context;
		data = arraylist;
		imageLoader = new ImageLoader(context);
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		 return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		// Declare Variables
		final ViewHolder holder;
		 if (convertView == null) {
		        convertView = mInflater.inflate(R.layout.languageapp_discover_video, null);
		        holder = new ViewHolder();
		        holder.first_name = (TextView) convertView.findViewById(R.id.firstname);
		        holder.user_role = (TextView) convertView.findViewById(R.id.userrole);
		        holder.display_dialect = (Button) convertView.findViewById(R.id.display_dialect);
		        holder.display_location = (Button) convertView.findViewById(R.id.display_location);
		        holder.setLikeAction = (Button) convertView.findViewById(R.id.setLikeAction);
		        holder.setDefAction = (Button) convertView.findViewById(R.id.setDefAction);
		        holder.urlreader = (Button) convertView.findViewById(R.id.urlreader);
		        holder.userimage = (ImageView) convertView.findViewById(R.id.userimggriditem);
		     
		        convertView.setTag(holder);
		    } else {
		        holder = (ViewHolder) convertView.getTag();
		    }


		resultp = data.get(position);
		
		
		imageLoader.DisplayImage(resultp.get(Maori_Discover_Word_Details.getIMAGEMID()), holder.userimage);
		holder.first_name.setText(resultp.get(Maori_Discover_Word_Details.getIMAGEfirst_name()) + " " +resultp.get(Maori_Discover_Word_Details.getIMAGElast_name()));
		holder.user_role.setText(resultp.get(Maori_Discover_Word_Details.getSYNtribe()));
		holder.display_dialect.setText(resultp.get(Maori_Discover_Word_Details.getAudioSyndialact()));
		holder.display_location.setText(resultp.get(Maori_Discover_Word_Details.getSYNcurrent_location()));
		holder.setLikeAction.setText("Like (" + resultp.get(Maori_Discover_Word_Details.getIMAGETotalsLikes()) + ")");
		
		MediaUID = resultp.get(Maori_Discover_Word_Details.getMediaUID());
		NodeMediaType = resultp.get(Maori_Discover_Word_Details.getNodeMediaType());
		
		UserLikedVideo = resultp.get(Maori_Discover_Word_Details.getUserLikedVideo());
		VideoParentNID = resultp.get(Maori_Discover_Word_Details.getVideoParentNID());
		VideoParentUID = resultp.get(Maori_Discover_Word_Details.getVideoParentUID());
		TotalsSetDefaultVideo = resultp.get(Maori_Discover_Word_Details.getTotalsSetDefaultVideo());
		NodeMediaSourceUrl = resultp.get(Maori_Discover_Word_Details.getIMAGEM_Source());
		/********** if user liked Like Button Set to Active ******************/
		
		if(TotalsSetDefaultVideo.equals("0")){
			holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_inactive, 0, 0, 0);
		}
		else{
			holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_active, 0, 0, 0);
		}
		/********** if user liked Like Button Set to Active ******************/
		
		Log.v("UserLikedAudio ", ":" + UserLikedVideo);
		if (UserLikedVideo.equals("0")) {
			holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_inactive_h, 0, 0, 0);
		} else {
			holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_h, 0, 0, 0);
		}

		holder.setDefAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				TotalsSetDefaultVideo = resultp.get(Maori_Discover_Word_Details.getTotalsSetDefaultVideo());

				if(TotalsSetDefaultVideo.equals("0")){
					holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_active, 0, 0, 0);
				}
				else{
					holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_inactive, 0, 0, 0);
				}
				resultp = data.get(position);
				SynUserID = resultp.get(Maori_Discover_Word_Details.getVideoParentUID());
				SynNodeId = resultp.get(Maori_Discover_Word_Details.getIMAGENM_ID());
				SynParentNodeId = resultp.get(Maori_Discover_Word_Details.getVideoParentNID());
				SynMediaType = "3";
				Log.v("TAG", "DEF SynUserID*********:" + SynUserID);
				Log.v("TAG", "DEF SynNodeId*********:" + SynNodeId);
				Log.v("TAG", "DEF SynParentNodeId***:" + SynParentNodeId);
				Log.v("TAG", "DEF SynMediaType******:" + SynMediaType);
				
				new UploadSetDefaultDetails().execute();
			}
		});

		imageLoader.DisplayImage(resultp.get(Maori_Discover_Word_Details.getIMAGEMID()), holder.userimage);
		holder.first_name.setText(resultp
				.get(Maori_Discover_Word_Details.getIMAGEfirst_name())
				+ " "
				+ resultp.get(Maori_Discover_Word_Details.getIMAGElast_name()));
		holder.user_role.setText(resultp.get(Maori_Discover_Word_Details.getSYNrole()));
		holder.display_dialect.setText(resultp.get(Maori_Discover_Word_Details.getVideoSyndialact()));
		holder.display_location.setText(resultp.get(Maori_Discover_Word_Details.getSYNcurrent_location()));
		holder.setLikeAction.setText("Like ("
				+ resultp.get(Maori_Discover_Word_Details.getIMAGETotalsLikes())
				+ ")");

		UserLikedVideo = resultp.get(Maori_Discover_Word_Details.getUserLikedVideo());
		VideoParentNID = resultp.get(Maori_Discover_Word_Details.getVideoParentNID());
		VideoParentUID = resultp.get(Maori_Discover_Word_Details.getVideoParentUID());

		/********** if user liked Like Button Set to Active ******************/
		if (UserLikedVideo.equals("0")) {
			holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_like_inactive_h, 0, 0, 0);
		} else {
			holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_like_h, 0, 0, 0);
		}

		// Capture button clicks on ListView items
		holder.urlreader.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Get the position from the results
				final Dialog dialog=new Dialog(context);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.languageapp_curate_video_dialog);
				
				final VideoView video_view = (VideoView) dialog.findViewById(R.id.curate_video_view);
				final ImageView image_view = (ImageView) dialog.findViewById(R.id.thubanail_view);
				final ProgressBar prog_view = (ProgressBar) dialog.findViewById(R.id.progressBar1);
				Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(NodeMediaSourceUrl, MediaStore.Images.Thumbnails.MINI_KIND);
				image_view.setImageBitmap(thumbnail);
				final MediaController mediaController = new MediaController(context);
			    mediaController.show();
			    mediaController.setAnchorView(video_view);
		        video_view.setMediaController(mediaController);
		        video_view.setVideoURI(Uri.parse(NodeMediaSourceUrl));
		        video_view.setZOrderOnTop(true);
		        video_view.requestFocus();
		        image_view.setVisibility(View.VISIBLE);
		   	 	prog_view.setVisibility(View.VISIBLE);
		   	 	
		   	   video_view.setOnTouchListener(new View.OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						mediaController.show();
						return true;
					}
		   	 	});
		   	 	
			    video_view.setOnPreparedListener(new OnPreparedListener() {
		             public void onPrepared(MediaPlayer mp) {
		            	 prog_view.setVisibility(View.GONE);
		            	 image_view.setVisibility(View.GONE);
		            	 video_view.start();
		             }
		            });
				
				dialog.show();
				
			}
		});

		holder.setLikeAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				HashMap<String, String> resultp = new HashMap<String, String>();
				resultp = data.get(position);
				VideoParentUID = resultp
						.get(Maori_Discover_Word_Details.getVideoParentUID());
				VideoNID = resultp.get(Maori_Discover_Word_Details.getIMAGENID());
				VideoParentNodeId = resultp
						.get(Maori_Discover_Word_Details.getVideoParentNID());
				VideoLikedByUser = resultp
						.get(Maori_Discover_Word_Details.getUserLikedVideo());
				VideoMediaID = resultp
						.get(Maori_Discover_Word_Details.getIMAGENM_ID());
				
				String TotalLikesAudio =resultp.get(Maori_Discover_Word_Details.getIMAGETotalsLikes());
				int TotalLikesVal = Integer.parseInt(TotalLikesAudio);
				
				if (VideoLikedByUser.equals("0")) {
					VideoLikedByUser = "1";
					holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_h, 0, 0, 0);
					TotalLikesVal = TotalLikesVal + 1;
					holder.setLikeAction.setText("Like (" + ""+ TotalLikesVal + ")");
					
					//Update Values Of the Hash Map Position
					resultp.put("IMAGETotalsLikes", "" + TotalLikesVal);
					resultp.put("UserLikedVideo", VideoLikedByUser);
				} 
				else {
					VideoLikedByUser = "0";
					holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_inactive_h, 0, 0, 0);
					TotalLikesVal = TotalLikesVal - 1;
					holder.setLikeAction.setText("Like (" + ""+ TotalLikesVal + ")");
					
					//Update Values Of the Hash Map Position
					resultp.put("IMAGETotalsLikes", "" + TotalLikesVal);
					resultp.put("UserLikedVideo", VideoLikedByUser);
				}
				
				
				
				new UploadLikeStateDetails().execute();
			}
		});



		return convertView;
	}

	
	static class ViewHolder {
		Button setDefAction;
		Button setLikeAction;
		Button urlreader;
		TextView first_name;
		TextView last_name;
		TextView  user_role;
		ImageView userimage;
		Button display_location;
		Button display_dialect;

	}
	
	
	
	private class UploadLikeStateDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();
				httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/saveNodeMediaLike.php");
				// Selected Type ID / content_type_id
				Log.e("SYN", "NID : " + VideoNID);
				Log.e("SYN", "UID : " + VideoParentUID);
				json.put("record1", VideoNID);
				json.put("record2", VideoParentUID);
				json.put("record3", "3");
				json.put("record4", VideoMediaID);

				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();

			}
			return null;
		}
		@Override
		protected void onPostExecute(Void args) {
			Log.v("LIKE VideoNID ", ":" + VideoNID);
			Log.v("LIKE VideoParentUID ", ":" + VideoParentUID);
			/*Intent intent = new Intent(context,
					Maori_Discover_Word_Details.class);
			intent.putExtra("nid", AudioParentNID);
			context.startActivity(intent);*/
		}
	}
	private class UploadSetDefaultDetails extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();
				httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/saveUsersSetDefaults.php");
				// Selected Type ID / content_type_id
				json.put("record1", SynUserID);
				// Selected UID / added_by
				json.put("record2", SynNodeId);

				json.put("record3", SynMediaType);

				json.put("record4", SynParentNodeId);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.v("TAG","POST SET DEF : " + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					Log.v("TAG", "Print Res***:" + result);
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			Intent intent = new Intent(context,
					Maori_Discover_Word_Details.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
			intent.putExtra("nid", SynParentNodeId);
			context.startActivity(intent);
			((Maori_Discover_Word_Details)context).finish();
		}
	}

}
